import json

from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods import models
from apps.goods.models import SKU
from utils.response_code import RETCODE
from utils.cookiesecret import CookieSecret


class CartsSimpleView(View):
    def get(self, request):
        if request.user.is_authenticated:
            redis_client = get_redis_connection('carts')
            carts_data = redis_client.hgetall(request.user.id)
            # carts_dict = {}
            # for key,value in carts_data.items():
            #     sku_key = int(key.decode())
            #     sku_value = json.loads(value.decode())
            #     carts_dict[sku_key] = sku_value
            carts_dict = {int(key.decode()):json.loads(value.decode()) for key,value in carts_data.items()}
        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
        skus = SKU.objects.filter(id__in = carts_dict.keys())
        skus_list = []
        for sku in skus:
            skus_list.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

            # 响应json列表数据
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': skus_list})

# 全选
class SelectedAllView(View):
    def put(self, request):

        # 1.接收参数
        selected = json.loads(request.body.decode()).get('selected')
        # 2. 解析校验
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('类型错误')

        # 3.判断是否登录
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        if user.is_authenticated:
            # redis
            client = get_redis_connection('carts')
            client_data = client.hgetall(user.id)

            # 遍历每一个商品 修改 选中状态
            for key, value in client_data.items():
                sku_id = int(key.decode())
                cart_dict = json.loads(value.decode())

                # 统一修改  所有选中状态
                cart_dict['selected'] = selected

                client.hset(user.id, sku_id, json.dumps(cart_dict))

        else:
            # cookie
            cookie_str = request.COOKIES.get('carts')

            if cookie_str is not None:
                cart_dict = CookieSecret.loads(cookie_str)

                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected

                dumps_cookie_str = CookieSecret.dumps(cart_dict)

                response.set_cookie('carts', dumps_cookie_str, max_age=24 * 15 * 3600)


        # 4.返回响应
        return response


class CartsView(View):
    # 1.增加
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 2.校验参数
        # 2.1 商品是否存在
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('商品不存在')

        # 2.2 count 是不是 int
        try:
            count = int(count)
        except:
            return http.HttpResponseForbidden('count类型不是整型!')
        # 2.3 selected 是不是boolean
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('selectd类型不是布尔类型!')

        # 3.判断是否登录
        user = request.user
        if user.is_authenticated:
            # 登录 redis
            print('登录 redis')
            # 1.链接数据库 redis
            redis_client = get_redis_connection('carts')

            # 2.取出所有的数据 hgetall
            client_data = redis_client.hgetall(user.id)

            # 3.判断是否存在 该用户是否有商品的记录数据
            if not client_data:
                # 新建 新增一条数据
                redis_client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            # 4.判断当前添加的商品 是否存在
            # client_data 内部数据格式 {b'3':b'{"count":2,"selected":true}'}
            if str(sku_id).encode() in client_data:
                # 修改count
                print('111')
                sku_dict = json.loads(client_data[str(sku_id).encode()].decode())
                print(sku_dict)
                # 累加 前端传入的个数
                sku_dict['count'] += count

                # 更新数据
                redis_client.hset(user.id, sku_id, json.dumps(sku_dict))

            else:
                # 商品不存在 新建一条数据
                print('222')
                redis_client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            # 5.返回响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})


        else:
            # 未登录 cookie
            print('未登录 cookie')

            # 1.查询cookie购物车数据
            cookie_str = request.COOKIES.get('carts')

            # 2. 判断有还是没有
            from utils.cookiesecret import CookieSecret
            if cookie_str:
                # 3.解密
                cookie_dict = CookieSecret.loads(cookie_str)
            else:
                cookie_dict = {}

            # 判断商品是否 存在购物车里面
            if sku_id in cookie_dict:
                original_count = cookie_dict[sku_id]['count']
                count += original_count

            # 4.修改 count selected
            cookie_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 5.加密
            dumps_cookie_str = CookieSecret.dumps(cookie_dict)

            # 6. 设置增加 set_cookie()
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', dumps_cookie_str, max_age=15 * 24 * 3500)

            # 7. 返回响应
            return response

    # 2.查询
    def get(self, request):

        # 1.判断是否登录
        user = request.user
        if user.is_authenticated:
            # redis
            # 1.链接数据库
            redis_client = get_redis_connection('carts')

            # 2. 取出该用户 所有购物车数据
            redis_carts_dict = redis_client.hgetall(user.id)

            # 3.字典推导式
            carts_dict = {}
            for key, value in redis_carts_dict.items():
                sku_id = int(key.decode())
                sku_value = json.loads(value.decode())
                carts_dict[sku_id] = sku_value

                # carts_dict = {int(key.decode()): json.loads(value.decode()) for key, value in redis_carts_dict.items()}
                # data[0] data[1] 是因为 for data in dict.items():  data 是个元祖
                # carts_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in carts_data.items()}

        else:
            # cookie
            cookie_str = request.COOKIES.get('carts')

            if cookie_str:

                carts_dict = CookieSecret.loads(cookie_str)
            else:

                carts_dict = {}

        sku_ids = carts_dict.keys()
        # 根据范围查询 获取 所有的商品对象
        skus = SKU.objects.filter(id__in=sku_ids)
        carts_list = []
        for sku in skus:
            sku_count = carts_dict.get(sku.id).get('count')
            carts_list.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * sku_count)
            })

        context = {
            'cart_skus': carts_list
        }

        return render(request, 'cart.html', context)

    # 3.修改
    def put(self, request):

        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = models.SKU.objects.get(id=sku_id)
        except models.SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 3.判断是否登录
        dumps_cookie_str = ""
        user = request.user
        if user.is_authenticated:
            # redis
            # 1.链接
            client = get_redis_connection('carts')

            # 2.修改
            client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

        else:
            # cookie
            cookie_str = request.COOKIES.get('carts')

            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

            # 修改 购物车的数据
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 加密
            dumps_cookie_str = CookieSecret.dumps(cart_dict)

        # 4.前端数据格式 组合
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }

        # 5.返回响应对象
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:
            response.set_cookie('carts', dumps_cookie_str, max_age=24 * 15 * 3600)
        return response

    # 4.删除
    def delete(self, request):

        # 1.接收参数
        sku_id = json.loads(request.body.decode()).get('sku_id')
        # 2.校验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseForbidden('商品不存在!')

        # 3. 判断是否登录
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

        if user.is_authenticated:
            # redis
            client = get_redis_connection('carts')
            client.hdel(user.id, sku_id)
        else:
            # cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 转成明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                del cart_dict[sku_id]

                # 加密
                dumps_cookie_str = CookieSecret.dumps(cart_dict)

                response.set_cookie('carts', dumps_cookie_str, max_age=24 * 15 * 3600)

        return response
